package com.person.monitor;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView listView;

    LogListAdapter logListAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view->startActivity(new Intent(MainActivity.this,ProcessListActivity.class)));

        listView = findViewById(R.id.list_view);
        logListAdapter = new LogListAdapter(this);
        listView.setAdapter(logListAdapter);
        logListAdapter.setLogList(LogcatHelper.getInstance().getLogList());

        phonePermissions();

        //OpenXiaomiProcess.startService(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        if (event.what == EventMessage.EVENT_NEW_LOG){
            logListAdapter.notifyDataSetChanged();
            MyLog.D("LogcatHelper.getInstance().getLogList().size()="+LogcatHelper.getInstance().getLogList().size());
        }
    }

    private void loadApps() {
        PackageManager packageManager = getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> list = packageManager.queryIntentActivities(mainIntent, 0);

        for(ResolveInfo resolveInfo:list){
            String label = resolveInfo.loadLabel(packageManager).toString();
            String packageName = resolveInfo.activityInfo.packageName;
            String activityName = resolveInfo.activityInfo.name;
            MyLog.D("label="+label+","+packageName+"/"+activityName);
        }
    }

    private void openIgnoringBattery(){

        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);

        boolean isIgnoringBattery = pm.isIgnoringBatteryOptimizations(getPackageName());

        if (!isIgnoringBattery) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 100);
        }

        MyLog.D("isIgnoringBattery="+isIgnoringBattery);
    }

    private void checkPermissions(){
        List<String> permissionList = new ArrayList<>();

        permissionList.add("android.permission.ACCESS_COARSE_LOCATION");
        permissionList.add("android.permission.ACCESS_FINE_LOCATION");
        permissionList.add("android.permission.ACCESS_BACKGROUND_LOCATION");

        XXPermissions.with(this)
                .permission(permissionList)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        MyLog.D("XXPermissions onDenied, size="+permissions.size()+",all="+all);
                        openIgnoringBattery();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        MyLog.D("XXPermissions onDenied, size="+permissions.size()+",never="+never);

                    }
                });
    }

    private void phonePermissions(){
        List<String> permissionList = new ArrayList<>();

        permissionList.add("android.permission.READ_PHONE_STATE");
        permissionList.add("android.permission.SYSTEM_ALERT_WINDOW");

        XXPermissions.with(this)
                .permission(permissionList)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        MyLog.D("XXPermissions onDenied, size="+permissions.size()+",all="+all);
                        checkPermissions();

                        getPersimmions();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        MyLog.D("XXPermissions onDenied, size="+permissions.size()+",never="+never);

                    }
                });
    }

    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }

            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), 200);
            }
        }
    }

    public void printProcessName() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();

        if (info == null || info.size() == 0) return;

        for (ActivityManager.RunningAppProcessInfo aInfo : info) {
            MyLog.D("printProcessName processName = "+aInfo.processName);
        }
    }

    public static void printProc(){
        File procDir = new File("/proc");
        File[] procFiles = procDir.listFiles();
        if (procFiles != null) {
            for (File pidDir : procFiles) {
                if (pidDir.isDirectory() && TextUtils.isDigitsOnly(pidDir.getName())) {
                    try (BufferedReader reader = new BufferedReader(new FileReader(pidDir.getAbsolutePath() + "/cmdline"))) {
                        String cmdline = reader.readLine();
                        MyLog.D("printProc cmdline = " + cmdline);
                    } catch (IOException ignored) {}
                }
            }
        }

    }

    public static void printUsageStatsManager(Context context){
        // 需要声明权限：android.permission.PACKAGE_USAGE_STATS
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long currentTime = System.currentTimeMillis();
// 获取最近1小时的应用使用记录
        List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, currentTime - 3600000, currentTime);
        for (UsageStats stat : stats) {
            MyLog.D("printUsageStatsManager stat = " + stat.getPackageName()+",LastTimeUsed="+stat.getLastTimeUsed());
        }

    }

    public boolean isProcessRunning() {
        try {
            StringBuilder builder = new StringBuilder("isProcessRunning ps:\r\n");

            Process process = Runtime.getRuntime().exec("ps -A"); // 列出所有进程

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            MyLog.D(builder.toString());

            process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
